package com.example.boardroom.demo.times;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.boardroom.R;
import com.example.boardroom.demo.Content;
import com.example.boardroom.demo.room.AppDatabase;
import com.example.boardroom.demo.room.HardwareControlDao;
import com.example.boardroom.demo.room.HardwareControlTable;
import com.example.boardroom.newItems.HardBean;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Timer;
import java.util.TimerTask;

public class HardwareService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private static final String TAG = "hello_lufei";
    public static final String CHANNEL_ID_STRING = "service_01";
    private Notification notification;
    @Override
    public void onCreate() {
        super.onCreate();
        dao = AppDatabase.getInstance(this).hardwareControlDao();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "服务启动", Toast.LENGTH_SHORT).show();
        //下面是判断 Android8.0 以后的服务,设置为后台服务的操作
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            //注意 startForeground(1, notification);中不能为0，不然会出现如下问题
            //Context.startForegroundService() did not then call Service.startForeground()
            startForeground(1, notification);
        }

        startTime();
        return super.onStartCommand(intent, flags, startId);
    }

    private Timer timer = null;//计时器
    private TimerTask task = null;

    //启动
    private void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Log.i("lufei", "此处自己设置");
                try {
                    //此处自己设置
                    getHardwareList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        };
        //1000ms执行一次
        timer.schedule(task, 1000, 2000);
    }

    //关闭
    private void stopTime() {
        if (timer != null)
            timer.cancel();
        timer = null;//据说这样不会自动跳出软件
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    /**
     * 获取硬件列表
     */
    private void getHardwareList() {

        OkGo.<String>get(Content.baseUrl + "applet/device/queryDevicesInfosByArea?areaId=4")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("lufei_response11", response.toString(), response.body());
                        HardBean hardBean = GsonUtils.fromJson(response.body(), HardBean.class);
                        storedInTheDatabase(hardBean);

                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    HardwareControlDao dao;

    /**
     * 设备列表存入数据库
     */
    private void storedInTheDatabase(HardBean hardBean) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (HardBean.DataDTO datum : hardBean.data) {
                    //处理掉空调的特殊字段
                    if (datum.deviceType.equals("aircondition_control") && !datum.openStatus.equals("2")) {
                        datum.openStatus = "1";
                        dao.insertAll(new HardwareControlTable(TimeUtils.getNowString(), datum));
                    } else {
                        dao.insertAll(new HardwareControlTable(TimeUtils.getNowString(), datum));
                    }

                }

            }
        }).start();

    }
}
